package com.yunsc.order.sevice.impl;

import com.yunsc.common.exception.YunscException;
import com.yunsc.order.dto.OrderPayDTO;
import com.yunsc.order.entity.YunscOrderEntity;
import com.yunsc.order.entity.YunscOrderGoodsEntity;
import com.yunsc.order.entity.YunscPaymentEntity;
import com.yunsc.order.sevice.*;
import com.yunsc.order.vo.OrderInfoVO;
import com.yunsc.order.vo.PersonalVO;
import com.yunsc.product.service.YunscGoodsService;
import com.yunsc.store.entity.YunscUserEntity;
import com.yunsc.store.service.YunscStoreSettingService;
import com.yunsc.store.service.YunscUserBalanceLogService;
import com.yunsc.store.service.YunscUserService;
import com.yunsc.store.vo.OrderSettingVO;
import com.yunsc.store.vo.UnpaidOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * @version: 1.0
 * @Author: adan
 * @description:
 * @date: 2024-05-20 11:51
 */
@Service
public class OrderPaymentServiceImpl implements OrderPaymentService {

    @Resource
    private YunscOrderService orderService;
    @Resource
    private YunscUserService userService;
    @Resource
    private YunscUserBalanceLogService userBalanceLogService;
    @Resource
    private YunscOrderGoodsService orderGoodsService;
    @Resource
    private YunscGoodsService goodsService;
    @Resource
    private OrderPaymentService orderPaymentService;
    @Resource
    private YunscStoreSettingService storeSettingService;
    @Resource
    private YunscPaymentService paymentService;


    @Override
    @Transactional
    public void orderPay(OrderPayDTO params, Integer userId, Integer storeId) {
        // 获取订单支付方式
        String method = params.getMethod();  // 1.微信wechat 2.支付宝alipay 3.余额balance
        // 调用支付接口
        // 1.微信支付
        if ("wechat".equals(method)) {
            // 微信支付, 微信支付接口调用
            orderPaymentService.wechatPay(params, userId, storeId);
        }

        // 2.支付宝支付
        if ("alipay".equals(method)) {
            // 支付宝支付
            orderPaymentService.alipayPay(params, userId, storeId);
        }

        // 3.余额支付
        if ("balance".equals(method)) {
            // 余额支付
            orderPaymentService.balancePay(params.getOrderId(), params.getMethod(), userId, storeId);
        }
    }

    @Override
    @Transactional
    public void balancePay(Integer orderId, String method, int userId, int storeId) {
        // 余额支付
        // 1.获取待支付订单
        YunscOrderEntity order = orderService.getById(orderId);
        if (order == null || order.getUserId() == null || !order.getUserId().equals(userId)) {
            // 订单不存在或订单用户与当前用户不匹配
            throw new YunscException("订单不存在或订单用户与当前用户不匹配");
        }

        // 付款状态(10未付款 20已付款)
        if (order.getPayStatus() == 20) {
            throw new YunscException("订单已支付");
        }

        // 余额支付
        // 2.获取用户余额
        YunscUserEntity user = userService.getById(userId);
        if (user == null) {
            // 用户不存在
            throw new YunscException("用户不存在");
        } else if (user.getBalance() == null || new BigDecimal(user.getBalance()).compareTo(new BigDecimal(order.getPayPrice())) < 0) {
            // 余额不足
            throw new YunscException("余额不足");
        }

        // 3.扣除用户余额
        user.setBalance(new BigDecimal(user.getBalance()).subtract(new BigDecimal(order.getPayPrice())).toString());
        userService.updateById(user);

        // 4.记录用户余额变动日志（20 用户消费）
        // userBalanceLogService.insertUserBalanceLog(userId, 20, order.getOrderNo(), order.getPayPrice(), storeId);
        String msg = "用户消费：" + order.getOrderNo();
        userBalanceLogService.addUserBalanceLog(userId, 20, "", msg, "-" + order.getPayPrice(), storeId);

        // 5.更新订单支付状态
        order.setPayStatus(20);
        order.setPayMethod(method);
        order.setPayTime((int) (System.currentTimeMillis() / 1000));
        orderService.updateById(order);

        // 订单支付成功
        // 6.减少商品库存
        List<YunscOrderGoodsEntity> orderGoodsList = orderGoodsService.queryOrderGoodsListByOrderId(orderId);
        orderGoodsList.forEach(orderGoods -> {
            // 库存计算方式(10下单减库存 20付款减库存)
            if (orderGoods.getDeductStockType() == 20) {
                // 付款减库存
                goodsService.deductStock(orderGoods.getGoodsId(), orderGoods.getGoodsSkuId(), orderGoods.getTotalNum());
            }
        });
    }

    @Override
    public void wechatPay(OrderPayDTO params, Integer userId, Integer storeId) {

    }

    @Override
    public void alipayPay(OrderPayDTO params, Integer userId, Integer storeId) {

    }

    @Override
    public OrderInfoVO queryOrderInfo(int orderId, String client, Integer userId, Integer storeId) {
        // 1.获取订单信息
        YunscOrderEntity orderEntity = orderService.getById(orderId);
        // 获取过期时间 = 订单创建时间 + 过期时间（天）
        OrderSettingVO orderSettingVO = storeSettingService.queryOrderSettingVO(storeId);
        int closeHours = orderSettingVO.getOrder().getCloseHours();
        // 过期时间
        int expireTime = orderEntity.getCreateTime() + closeHours * 60 * 60;
        UnpaidOrder order = new UnpaidOrder();
        BeanUtils.copyProperties(orderEntity, order);
        order.setShowExpiration(true);
        order.setExpirationTime(expireTime);
        // 2. 获取支付方式
        List<YunscPaymentEntity> paymentList = paymentService.queryPaymentMethodsByClient(client, storeId);
        // 3. 获取用户信息
        YunscUserEntity userEntity = userService.getById(userId);
        PersonalVO personalVO = new PersonalVO();
        BeanUtils.copyProperties(userEntity, personalVO);

        OrderInfoVO orderInfoVO = new OrderInfoVO();
        orderInfoVO.setOrder(order);
        orderInfoVO.setPaymentMethods(paymentList);
        orderInfoVO.setPersonal(personalVO);
        return orderInfoVO;
    }

}
